﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ServiceModel;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Configuration;
using System.ServiceModel.Configuration;

namespace WcfCore
{
	public static class WcfServiceHostFactory
	{
		//private const string _serviceModelSectionGroupName = "system.serviceModel";
		//private const string _bindingsConfigSectionName = "system.serviceModel/bindings";

		public static ServiceHost CreateHost(WcfTestInput input)
		{
			WcfLogger.Log(string.Format("Opening host in  AppDomain id: {0}", AppDomain.CurrentDomain.Id));
			if (input.Binding.Equals(Bindings.Remoting))
			{
				Hashtable properties = new Hashtable();
				properties.Add("port", WcfTestInput.RemotingPortNumber);
				BinaryServerFormatterSinkProvider srvSinkProv = new BinaryServerFormatterSinkProvider();
				srvSinkProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
				BinaryClientFormatterSinkProvider cliSinkProv = new BinaryClientFormatterSinkProvider();
				TcpChannel channel = new TcpChannel(properties, cliSinkProv, srvSinkProv);
				ChannelServices.RegisterChannel(channel, false);

				switch (input.InstancingMode)
				{
					case InstanceContextMode.PerCall:
						RemotingConfiguration.RegisterWellKnownServiceType(input.ServiceType, input.RemotingObjectUri, WellKnownObjectMode.SingleCall);
						break;
					default:
						RemotingConfiguration.RegisterWellKnownServiceType(input.ServiceType, input.RemotingObjectUri, WellKnownObjectMode.Singleton);
						break;
				}
				return null;
			}
			else
			{
				// The bloody overriding of configuration JUST DOESN'T WORK.
				//// Override Binding configSource
				//Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
				////ServiceModelSectionGroup smsg = (ServiceModelSectionGroup)config.GetSectionGroup(_serviceModelSectionGroupName);
				////smsg.Bindings.SectionInformation.ConfigSource = input.BindingConfig;
				//BindingsSection bs = (BindingsSection)config.GetSection(_bindingsConfigSectionName);
				//bs.SectionInformation.ConfigSource = input.BindingConfig;
				//config.Save();
				//ConfigurationManager.RefreshSection(_serviceModelSectionGroupName);

				ServiceHost host = new ServiceHost(input.ServiceType);
				host.Open();
				return host;
			}
		}
	}
}
